/*
 * FileName：JobServiceImpl.java 
 * <p>
 * Copyright (c) 2017-2020 <a href="https://www.smartwx.info">hermit(1154808491@qq.com)</a>.
 * <p>
 * Licensed under the GNU General Public License, Version 3 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl-3.0.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package com.smart.quartz.service.impl;

import com.smart.quartz.entity.JobEntity;
import com.smart.quartz.service.IJobService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class JobServiceImpl implements IJobService {

    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    private Scheduler scheduler;


    @Override
    public List<JobEntity> quertListJobByPage(JobEntity job) {
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT job.JOB_NAME as jobName,job.JOB_GROUP as jobGroup,job.DESCRIPTION as jobDesc,job.JOB_CLASS_NAME as jobClassName,");
        sql.append("cron.CRON_EXPRESSION as jobCron,tri.TRIGGER_STATE as status,tri.PREV_FIRE_TIME as previousFireTime,tri.NEXT_FIRE_TIME as nextFireTime ");
        sql.append("FROM qrtz_job_details AS job LEFT JOIN qrtz_triggers AS tri ON job.JOB_NAME = tri.JOB_NAME ");
        sql.append("LEFT JOIN qrtz_cron_triggers AS cron ON cron.TRIGGER_NAME = tri.TRIGGER_NAME ");
        sql.append("WHERE tri.TRIGGER_TYPE = 'CRON'");
        if(!StringUtils.isEmpty(job.getJobName())){
            sql.append(" AND job.JOB_NAME = :jobName");
        }
        List list = jdbcTemplate.query(sql.toString(), new BeanPropertySqlParameterSource(job), new BeanPropertyRowMapper(JobEntity.class));
        return list;
    }

    @Override
    public void saveJob(JobEntity job) throws Exception {
        //构造触发类
        Class cls = Class.forName(job.getJobClassName()) ;
        cls.newInstance();
        //job
        JobDetail jobDetail = JobBuilder.newJob(cls).withIdentity(job.getJobName(),job.getJobGroup())
                .withDescription(job.getJobDesc()).storeDurably(true).build();
        // 触发器
        Trigger trigger = TriggerBuilder.newTrigger().withSchedule(CronScheduleBuilder.cronSchedule(job.getJobCron()))
                .withIdentity(job.getJobName(), job.getJobGroup())
                .withDescription(job.getJobDesc()).forJob(jobDetail).build();
        //触发job
        scheduler.scheduleJob(jobDetail, trigger);
    }

    @Override
    public void runJob(JobEntity job) throws Exception {
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        scheduler.triggerJob(jobKey);
    }

    @Override
    public void resumeJob(JobEntity job) throws  Exception {
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
        scheduler.resumeTrigger(triggerKey);
    }

    @Override
    public void pauseJob(JobEntity job) throws Exception {
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
        scheduler.pauseTrigger(triggerKey);
    }

    @Override
    public void deleteJob(JobEntity job) throws  Exception {
        JobKey jobKey = JobKey.jobKey(job.getJobName(), job.getJobGroup());
        TriggerKey triggerKey = TriggerKey.triggerKey(job.getJobName(), job.getJobGroup());
        // 停止触发器
        scheduler.pauseTrigger(triggerKey);
        // 移除触发器
        scheduler.unscheduleJob(triggerKey);
        // 删除任务
        scheduler.deleteJob(jobKey);
    }

    @Override
    public void updateJob(JobEntity job) throws Exception {
        //先删除再修改
        scheduler.deleteJob(JobKey.jobKey(job.getJobName(), job.getJobGroup()));
        this.saveJob(job);
    }
}
